package com.example.wangtieying.firtest;

import android.app.DownloadManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;

import java.io.File;

/**
 * Created by wangtieying on 16/7/23.
 */
public class DownloadService extends Service {
    public static Context context;
    private static String savePath = "/jyd/download/";

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    public void onDestroy() {
        super.onDestroy();
    }

    public static void downNewFile(final String url, final String name) {
        DataCleanManager.deleteFilesByDirectory(new File(context.getExternalFilesDir(null).getPath() + savePath, name));
        showNotice(url, name);
    }

    private static DownloadManager manager;
    private static long downLoadId;

    private static void
    showNotice(String url, String name) {
        manager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        /**
         * 设置下载地址
         */
        DownloadManager.Request down = new DownloadManager.Request(
                Uri.parse(url)
        );
        /**
         * 设置允许使用的网络类型,这里是移动和wifi都可以
         */
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        /**
         * 下载时,通知栏显示
         */
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        /**
         * 显示下载界面
         */
        down.setVisibleInDownloadsUi(true);
        /**
         * 设置下载后文件存放位置
         * 这里savePath是(如方法描述:ExternalFilesDir)当中的路径
         */
        down.setDestinationInExternalFilesDir(context, savePath, name);
        //将下载请求放入队列
        downLoadId = manager.enqueue(down);
        checkDownStatus(name);
    }

    static boolean finish = false;

    /**
     * 检查下载状态
     *
     * @param apkName
     */
    private static void checkDownStatus(final String apkName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!finish) {
                    queryDownloadStatus(apkName);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private static void queryDownloadStatus(String apkName) {
        DownloadManager.Query query = new DownloadManager.Query();
        Cursor c = manager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                case DownloadManager.STATUS_PENDING:
                case DownloadManager.STATUS_RUNNING:
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    finish = true;
                    installApk(apkName);
                    break;
                case DownloadManager.STATUS_FAILED:
                    DataCleanManager.deleteFilesByDirectory(new File(context.getExternalFilesDir(null).getPath() + savePath, apkName));
                    finish = true;
                    break;
            }
        }
        c.close();
    }

    private static void installApk(String apkName) {
        /**
         *
         */
        File apkfile = new File(context.getExternalFilesDir(null).getPath() + savePath, apkName);
        if (!apkfile.exists()) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //Uri.parse("file://" + apkfile.toString()) 路径
        //"application/vnd.android.package-archive"是文件类型，具体对应apk类型。
        intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

}
